package middleware

import (
	"asuOfficialApi/comm"
	"asuOfficialApi/service"
	"github.com/kataras/iris"
	"strings"
)

func New(s service.TokenService) iris.Handler {
	return func(ctx iris.Context) {
		uri := ctx.Request().RequestURI
		index := strings.Index(uri, "/anno/")

		if index != -1 {
			ctx.Next()
			return
		}

		loginUser := comm.GetLoginUser(ctx.Request())
		if loginUser != nil {
			ctx.Next()
			return
		}

		token := strings.TrimSpace(ctx.URLParam("token"))
		if token != "" {
			model := s.GetToken(token)
			if model != nil && model.Id > 0 {
				ctx.Next()
			} else {
				_, _ = ctx.JSON(comm.Fail(comm.ErrorNotExist, "token失效或者不存在"))
			}
		} else {
			_, _ = ctx.JSON(comm.Fail(comm.ErrorTokenNotSet, "token not set"))
		}
	}
}
